package com.itheima.project.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.logging.log4j2.Log4j2Impl;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import java.io.IOException;

@Configuration
@PropertySource(value ="classpath:db.properties")
@MapperScan(basePackages = {"com.itheima.project.mapper"},sqlSessionFactoryRef = "sqlSessionFactory")
public class myBatisConfig {

    @Value("${dataSource.driverClassName}")
    private String driverClassName;

    @Value("${dataSource.url}")
    private String url;

    @Value("${dataSource.username}")
    private String username;

    @Value("${dataSource.password}")
    private String password;
@Bean("druidDataSource")
    public DruidDataSource druidDataSource(){
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setDriverClassName(driverClassName);
    druidDataSource.setUrl(url);
    druidDataSource.setUsername(username);
    druidDataSource.setPassword(password);
    return druidDataSource;
}
@Bean("transactionManager")
    public DataSourceTransactionManager dataSourceTransactionManager(){
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
    transactionManager.setDataSource(druidDataSource());
    return transactionManager;
}
@Bean("sqlSessionFactory")
    public SqlSessionFactoryBean sessionFactoryBean(){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(druidDataSource());
        factoryBean.setTypeAliasesPackage("com.itheima.project.pojo");
    try {
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("sqlMapper/*Mapper.xml"));
    } catch (IOException e) {
        e.printStackTrace();
    }
  org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
    configuration.setLogImpl(Log4j2Impl.class);
    factoryBean.setConfiguration(configuration);
    return factoryBean;
}
}
